const Koa = require('koa');
const http = require('http');
const config = require('./app/config/config');
const bodyparser = require('./app/middleware/bodyparser');
const db = require('./app/middleware/mysql');
const bodyParser = require('koa-bodyparser');
const authenticate = require('./app/middleware/authenticate');
const cors = require('./app/middleware/cors');
const handleWS = require('./app/middleware/websocket');
const router = require('./router');
const io = require('socket.io');
const app = new Koa();

/**
 * cors middleware
 */
app.use(cors);

/**
 * websocket
 */
app.use(handleWS());
app.use(bodyparser);
// app.use(bodyParser());
app.use(db());
app.use(authenticate.auth);
app.use(router.routes()).use(router.allowedMethods());


const httpServer = http.createServer(app.callback());

const websocketServer = io(httpServer, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    },
    withCredentials: true
});


// collect socket to publish room
websocketServer.on('connect', socket => {
    // console.log(socket.id);
    socket.join('publish');

    socket.on('message', data => {
        socket.send('hi');
    });
});

global.websocketServer = websocketServer;
httpServer.listen(config.server.port, () => {
    console.log(`bundle server started at ${config.server.port}`)
});